I am trying to make use of sed to make a small change in the below myfileforsed.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
My requirement:
I want to change admin:add:4527:foo/faa into admin:add:4527:foo/free
However I am not able to do it with :
cat myfileforsed.txt | grep -w admin | sed -i 's/faa/free/'
sed: no input files
It is because I am not giving input of file in last.
Can someone suggest me what can be done to achieve this as a single line with sed?
Instead of sed, do you have any other suggestions too as I am new to this world of linux ?
CodePudding user response:
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.
CodePudding user response:
Simple sed scripts follow the pattern "filter operation arguments". If you want to substitute text in all lines matching a pattern, use the following sed script: /\word\b/s/foo/bar/. The -i flag tells flag to edit the file in-place, but for this you need to pass a file path to sed and not feed text through stdin.
sed -i '/\badmin\b/s/faa/free/' myfileforsed.txt
If you still want/need to combine sed with other programs, write the output to a temporary file and then copy its content over the original file:
grep -w 'admin' myfileforsed.txt | sed 's/faa/free/' > tmp.txt && cat tmp.txt > myfileforsed.txt
