Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

linux - How can I prepend a string to the beginning of each line in a file?

I have the following bash code which loops through a text file, line by line .. im trying to prefix the work 'prefix' to each line but instead am getting this error:

rob@laptop:~/Desktop$ ./appendToFile.sh stusers.txt kp
stusers.txt
kp
./appendToFile.sh: line 11: /bin/sed: Argument list too long
[email protected],passw0rd

This is the bash script ..

#!/bin/bash

file=$1
string=$2

echo "$file"
echo "$string"

for line in `cat $file`
do
    sed -e 's/^/prefix/' $line
    echo "$line"
done < $file

What am i doing wrong here?

Update: Performing head on file dumps all the lines onto a single line of the terminal, probably related?

rob@laptop:~/Desktop$ head stusers.txt
rob@laptop:~/Desktop$ ouse.com,passw0rd
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

a one-line awk command should do the trick also:

awk '{print "prefix" $0}' file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...