所以有人在推特上提到了这一点。你有一个像这样的文本文件:
watermelon
taco
bacon
cheese
您想在“taco”的末尾附加文字“kitten”。因此,所需的输出如下:
watermelon
tacokitten
bacon
cheese
你怎么能用bash做到这一点?
答案 0 :(得分:2)
没有任何关于此的特定内容;只需使用sed
程序:
sed 's/^\(taco\)$/\1kitten/' inputfile
答案 1 :(得分:1)
虽然sed
显然是一个更好的选择,但在学术上,这里是如何在纯bash(或zsh)中做到这一点:
while read line; do
if [ "$line" = "taco" ]; then
line=${line}kitten
fi
echo "$line"
done < test.in
或稍微更具惯用性:
while read line; do
[ "$line" = "taco" ] && line=${line}kitten
echo "$line"
done < test.in
或awk
:
awk '/^taco$/{$0=$0"kitten"}1' test.in
答案 2 :(得分:0)
显式:
TARGET_FILE=/path/to/file.txt
LINENO=1 # line number counter
NEEDLE="taco"
for word in $(cat $TARGET_FILE)
do
if [ "$word" = $NEEDLE ]
then
#echo "Appending $word on line $LINENO..."
sed -i "${LINENO}s/.*/${word}TEXTAPPENDED/" $TARGET_FILE
break
fi
LINENO=$(( LINENO +1 )) #increase line number by 1
done