grep + grep + sed = sed: no input files

好久不见. 提交于 2020-01-14 19:32:26

问题


Can anybody help me please?

grep " 287 " file.txt | grep "HI" | sed -i 's/HIS/HID/g' 

sed: no input files

Tried also xargs

grep " 287 " file.txt | grep HI | xargs sed -i 's/HIS/HID/g'
sed: invalid option -- '6'

This works fine

grep " 287 " file.txt | grep HI

回答1:


If you want to keep your pipeline:

f=file.txt
tmp=$(mktemp)
grep " 287 " "$f" | grep "HI" | sed 's/HIS/HID/g' > "$tmp" && mv "$tmp" "$f"

Or, simplify:

sed -i -n '/ 287 / {/HI/ s/HIS/HID/p}' file.txt

That will filter out any line that does not contain " 287 " and "HI" -- is that what you want? I suspect you really want this:

sed -i '/ 287 / {/HI/ s/HIS/HID/}' file.txt

For lines that match / 287 /, execute the commands in braces. In there, for lines that match /HI/, search for the first "HIS" and replace with "HID". sed implicitly prints all lines if -n is not specified.

Other commands that do the same thing:

awk '/ 287 / && /HI/ {sub(/HIS/, "HID")} {print}' file.txt > new.txt
perl -i -pe '/ 287 / and /HI/ and s/HIS/HID/' file.txt

awk does not have an "in-place" option (except gawk -i inplace for recent gawk versions)



来源:https://stackoverflow.com/questions/29284031/grep-grep-sed-sed-no-input-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!