1

I have the following data in a file:

col1 col2 col3 col4 col5 col6  
ABC DEF GE-10 0 0 12 4 16 0  
HIJ KLM 7 0 123 40 0 0  
NOP QL 17 0 0 6 10 1

I want to merge all text information into one string (with _ between) so that it looks like in this:

col1 col2 col3 col4 col5 col6  
ABC_DEF_GE-10 0 0 12 4 16 0  
HIJ_KLM 7 0 123 40 0 0  
NOP_QL 17 0 0 6 10 1

The issue is that the text information to be merged exists in col 1-2 for some rows and in col 1-3 in some rows.

How is this accomplished in Bash?

Angerfors
  • 11
  • 2

1 Answers1

0

test.js

#!/bin/bash.

file='read_file.txt'  
  
#Reading each line  
while read line; do
    #Reading each word  
    wordString=""
    count=1
    for word in $line; do
       if [[ $word =~ ^[0-9]+$ ]];then
            #starts with a numberic value
            wordString="${wordString} ${word}"
            else
            #doesn't starts with a numberic value
            wordString="${wordString}_${word}"
        fi
    done
#remove first character and print the line    
echo ${wordString#?}
done < $file  

put this in the below file in the same directory

read_file.txt

col1 col2 col3 col4 col5 col6  
ABC DEF GE-10 0 0 12 4 16 0  
HIJ KLM 7 0 123 40 0 0  
NOP QL 17 0 0 6 10 1
Mohit Hurkat
  • 406
  • 2
  • 8