所以推特上有人提到了这一点。你有一个像这样的文本文件:
watermelon
taco
bacon
cheese
您想将文本“kitten”附加到“taco”的末尾。因此,想要的输出是这样的:
watermelon
tacokitten
bacon
cheese
你怎么能在 bash 中做到这一点?
对此没有什么特别的 bash 。只需使用该sed
程序:
sed 's/^\(taco\)$/\1kitten/' inputfile
虽然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
Explicitly:
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