Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate strings in bash

Tags:

bash

I have in a bash script:

for i in `seq 1 10`
do
   read AA BB CC <<< $(cat file1 |  grep DATA)
   echo ${i}
   echo ${CC}
   SORT=${CC}${i}
   echo ${SORT}
done

so "i" is a integer, and CC is a string like "TODAY"

I would like to get then in SORT, "TODAY1", etc

But I get "1ODAY", "2ODAY" and so

Where is the error?

Thanks

like image 302
Open the way Avatar asked Mar 04 '10 13:03

Open the way


People also ask

How do I concatenate strings?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.

How do I append to a string in Linux?

String concatenation is the process of appending a string to the end of another string. This can be done with shell scripting using two methods: using the += operator, or simply writing strings one after the other.

What does concatenate do in Linux?

The cat (short for “concatenate“) command is one of the most frequently used commands in Linux/Unix-like operating systems. cat command allows us to create single or multiple files, view content of a file, concatenate files and redirect output in terminal or files.


2 Answers

You should try

SORT="${CC}${i}"

Make sure your file does not contain "\r" that would end just in the end of $CC. This could well explain why you get "1ODAY".

Try including |tr '\r' '' after the cat command

like image 180
tonio Avatar answered Sep 20 '22 23:09

tonio


try

   for i in {1..10}
    do
      while read -r line
      do
        case "$line" in
         *DATA* ) 
             set -- $line
             CC=$3
             SORT=${CC}${i}
             echo ${SORT}
        esac
      done <"file1" 
    done

Otherwise, show an example of file1 and your desired output

like image 44
ghostdog74 Avatar answered Sep 17 '22 23:09

ghostdog74