Sed to change specific file content permanently
Given:
cat fileforsed.txt
sameer:test:1234:foo/faa
saurabh:test:2313:foo/faa
john:test:2314:foo/faa
admin:add:4527:foo/faa
jane:test:2131:foo/faa
You can use sed
and sed alone to do:
sed -E 's/^(admin.*)faa$/\1free/' fileforsed.txt
sameer:test:1234:foo/faa
saurabh:test:2313:foo/faa
john:test:2314:foo/faa
admin:add:4527:foo/free
jane:test:2131:foo/faa
Once you have that working for stdin
THEN add the -i
flag.
sed -i'.bak' -E 's/^(admin.*)faa$/\1free/' fileforsed.txt
head fileforsed*
==> fileforsed.txt <==
sameer:test:1234:foo/faa
saurabh:test:2313:foo/faa
john:test:2314:foo/faa
admin:add:4527:foo/free
jane:test:2131:foo/faa
==> fileforsed.txt.bak <==
sameer:test:1234:foo/faa
saurabh:test:2313:foo/faa
john:test:2314:foo/faa
admin:add:4527:foo/faa
jane:test:2131:foo/faa
If you want to use variables in the sed script you can do this:
admin_var="admin"
replacement="free"
sed -i'.bak' -E 's/^('"$admin_var"'.*)faa$/\1'"$replacement/" fileforsed.txt
Or:
sed -i'.bak' -E "s/^(${admin_var}.*)faa$/\1${replacement}/" fileforsed.txt
(Note the quoting for both those.)
Note:
cat file | grep something | sed -i 's/this/that/'
will never work since sed is only taking stdin
input from grep
and there is no file to change. You can only output from sed to stdin
and redirect that output to a file. However -- this is not the way to get a line in any case. sed can both read a file and match a line in that file so both cat
and grep
are redundant.