Read line by line from a text file and print how I want in shell scripting

Viewed 743

I want to read below file line by line from a text file and print how I want in shell scripting

Text file content:   
zero#123456  
one#123  
two#12345678 

I want to print this as:

zero@1-6  
one@1-3  
two@1-8  

I tried the following:

file="readFile.txt"     
while IFS= read -r line    
do echo  "$line"     
done  <printf '%s\n' "$file"    
3 Answers

Create a script like below: my_print.sh

file="readFile.txt" 

while IFS= read -r line
do
one=$(echo $line| awk -F'#' '{print $1}') ## This splits the line based on '#' and picks the 1st value. So, we get zero from 'zero#123456 ' 
len=$(echo $line| awk -F'#' '{print $2}'|wc -c)  ## This takes the 2nd value which is 123456 and counts the number of characters
two=$(echo $line| awk -F'#' '{print $2}'| cut -c 1)  ## This picks the 1st character from '123456' which is 1
three=$(echo $line| awk -F'#' '{print $2}'| cut -c $((len-1)))  ## This picks the last character from '123456' which is 6
echo $one@$two-$three  ## This is basically printing the output in the format you wanted 'zero@1-6'
done <"$file"

Run it like:

mayankp@mayank:~/$ sh my_print.sh 
mayankp@mayank:~/$ cat output.txt 
zero@1-6
one@1-3
two@1-8

Let me know of this helps.

With sed:

sed -r 's/^(.+)#([0-9])[0-9]*([0-9])\s*$/\1@\2-\3/' readFile.txt
  • -r: using extented regular expressions (just to write some stuff without escaping them by a backslash)
  • s/expr1/expr2/: substitute expr1 by expr2
  • epxr1 is described by a regular expression, relevant matching patterns are caught by 3 capturing groups (parenthesized ones).
  • epxr2 retrieves captured strings (\1, \2, \3) and insert them in a formatted output (the one you wanted).

Regular-Expressions.info seems to be interesting to start with them. Also you can check your own regexp with Regx101.com.

Update: Also you could do that with awk:

awk -F'#' '{ \
             gsub(/\s*/,"", $2) ; \
             print $1 "@" substr($2, 1, 1) "-" substr($2, length($2), 1) \
           }' < test.txt

I added a gsub() call because your file seems to have trailing blank characters.

It's no shell scripting (missed that first, sorry) but using perl with combined lookahead and lookbehind for a number:

$ perl -pe 's/(?<=[0-9]).*(?=[0-9])/-/' file
Text file content:   
zero#1-6  
one#1-3  
two#1-8 

Explained some:

  • s//-/ replace with a -
  • (?<=[0-9]) positive lookbehind, if preceeded by a number
  • (?=[0-9]) positive lookahead, if followed by a number
Related