Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 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 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...