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

后端 未结 7 2090
轮回少年
轮回少年 2020-12-08 15:16

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:

7条回答
  •  半阙折子戏
    2020-12-08 16:00

    Concerning your original error:

    ./appendToFile.sh: line 11: /bin/sed: Argument list too long

    The problem is with this line of code:

    sed -e 's/^/prefix/' $line
    

    $line in this context is file name that sed is running against. To correct your code you should fix this line as such:

    echo $line | sed -e 's/^/prefix/'
    

    (Also note that your original code should not have the < $file at the end.)

    William Pursell addresses this issue correctly in both of his suggestions.

    However, I believe you have correctly identified that there is an issue with your original text file. dos2unix will not correct this issue, as it only strips the carriage returns Windows sticks on the end of lines. (However, if you are attempting to read a Linux file in Windows, you would get a mammoth line with no returns.)

    Assuming that it is not an issue with the end of line characters in your text file, William Pursell's, Andy Lester's, or nullrevolution's answers will work.

    A variation on the while read... suggestion:

    while read -r line; do  echo "PREFIX " $line; done < $file
    

    This could be run directly from the shell (no need for a batch / script file):

    while read -r line; do echo "kp" $line; done < stusers.txt
    

提交回复
热议问题