bobbyrne01 bobbyrne01 - 4 months ago 25
Linux Question

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
115000_210org@house.com,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

Answer

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

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