Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of lines of double quoted strings in a shell script

I'm trying to split a line with double quoted strings into an array:

input.txt:

"ABC" "This is TEST 1" "12.3.0"    
"AC" "This is TEST 221" "123"    
"CX" "This is TEST 16" "123.2"    
"LM" "This is TEST 9000" "123.6.6.1"

What I'm hoping to be the outcome for each line:

print $a[0] $a[1] $a[2]

ABC This is TEST 1 12.3.0

How best to grab each string per line? I'm trying to do this via command line and/or a shell script

Update: To help reduce complexity, I've updated my "input.txt" file as follows: input.txt:

'ABC' 'This is TEST 1' '12.3.0'    
'AC' 'This is "TEST" 221' '123'    
'CX' 'This is TEST 16' '123.2'    
'LM' 'This is TEST 9000' '123.6.6.1'

All the double quotes have been replaced with Single quotes, other that the ones with-in a value.

like image 851
user1916820 Avatar asked Nov 23 '25 20:11

user1916820


1 Answers

Assuming you are using bash:

IFS='"' a=("ABC" "This is TEST1" "12.3.0")

should almost work. The indexes will be off, with empty entries, but:

 while IFS='"' read -a a; do 
    echo ${a[1]} ${a[3]} ${a[5]}; done < input

gets you most of the way there. Keep in mind that this is pretty fragile.

like image 86
William Pursell Avatar answered Nov 26 '25 18:11

William Pursell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!