-1

I'm writing a simple shell script. This script read lines from a text file, and manipulate it. But I have a problem.

I want to attach a text to line from file.

line from file : /aaa/bbb/aaaaaaaa.java
I expect       : /aaa/bbb/aaaaaaaa.java_20221116
result is      : _20221116aaaaaaaa.java

What is I missing? Thanks.

Here is sample text file and script. [file.txt]

/aaa/bbb/aaaaaaaa.java
/aaa/bbb/bbbbbbbb.js
/aaa/bbb/cccccccc.xml

[test.sh]

#!/bin/bash

append=_20221116
while read line ; do
    echo " "
    echo "line : "$line
    line=$line$append
    echo $line
done < file.txt

echo " "
echo "### with variable text"
line=/aaa/bbb/ccc.txt
echo $line
echo $line"_20221116"

[Result]

[root@deploy]# ./test.sh
line : /aaa/bbb/aaaaaaaa.java
_20221116aaaaaaaa.java

line : /aaa/bbb/bbbbbbbb.js
_20221116bbbbbbbb.js

line : /aaa/bbb/cccccccc.xml
_20221116cccccccc.xml

### with variable text
/aaa/bbb/ccc.txt
/aaa/bbb/ccc.txt_20221116
  • 3
    You should edit your post and fix the code block formatting, but without looking much closer, I suspect your input file has carriage returns ("Windows line endings"); see [Are shell scripts sensitive to encoding and line endings?](https://stackoverflow.com/q/39527571/3266847) – Benjamin W. Nov 16 '22 at 05:04
  • Your script worked fine on my computer , so Benjamin is probably right. It is also best practice to do `"${var}"` to prevent globbing, for example: `line="${line}${append}"`. You also probably want to quote any string you assign since special characters will create errors, for example: `line='/aaa/bbb/ccc.txt'`. – Maximilian Ballard Nov 16 '22 at 06:58
  • Since after appending, the line is printed as `_20221116aaaaaaaa.java` instead of `/aaa/bbb/aaaaaaaa.java_20221116`, I conclude that there is a carriage return after _java_. You can verify this using `xxd <<<$line` instead of `echo $line`. – user1934428 Nov 16 '22 at 07:55

1 Answers1

0

Thanks all advices, especially Benjamin.

I solved this problem. It was "carriage return". So I changed my script. See below. It works nice.

while IFS=$'\r' read line ; do
        echo " "
        echo "line : "$line
        line=$line$append
        echo $line
done < file.txt