Reputation: 63885
So someone on twitter mentioned this. You have a text file like so:
watermelon
taco
bacon
cheese
You want to append the text "kitten" to the end of "taco". Thus, the wanted output is as so:
watermelon
tacokitten
bacon
cheese
How can you do this in bash?
Upvotes: 0
Views: 244
Reputation: 13549
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
Upvotes: 0
Reputation: 56129
While sed
is clearly a better choice, academically, here's how to do it in pure bash (or zsh):
while read line; do
if [ "$line" = "taco" ]; then
line=${line}kitten
fi
echo "$line"
done < test.in
Or slightly more idiomatically:
while read line; do
[ "$line" = "taco" ] && line=${line}kitten
echo "$line"
done < test.in
Or in awk
:
awk '/^taco$/{$0=$0"kitten"}1' test.in
Upvotes: 1
Reputation:
There's nothing bash specific about this; just use the sed
program:
sed 's/^\(taco\)$/\1kitten/' inputfile
Upvotes: 3