Home > OS >  how to change words with the same words but with number at the back bash
how to change words with the same words but with number at the back bash

Time:12-13

I have a file for example with the name file.csv and content

adult,REZ
man,BRB
women,SYO
animal,HIJ

and a line that is nor a directory nor a file

file.csv BRB1 REZ3 SYO2

And what I want to do is change the content of the file with the words that are on the line and then get the nth letter of that word with the number at the end of the those words in capital and the output should then be

umo

I know that I can get over the line with

for i in "${@:2}"
do
words =$(echo "$i ")
done

and then the output is

REZ3 BRB1 SYO2

I don't know how to continue but my desired output is this please

umo

CodePudding user response:

This is a way using sed. Create a pattern string from command arguments and convert lines with sed.

#!/bin/bash
file="$1"
pat='s/^/ /;Te;'
for i in ${@:2}; do
    pat =$(echo $i | sed 's#^\([^0-9]*\)\([0-9]*\)$#s/.\\{\2\\}\\(.\\).*,\1$/\\1/;#')
done
pat ='Te;H;:e;${x;s/\n//g;p}'
eval "sed -n '$pat' $file"

CodePudding user response:

Using awk:

Pass the string of values as an awk variable and then split them into an array a. For each record in file.csv, iterate this array and if the second field of current record matches the first three characters of the current array value, then strip the target character from the first field of the current record and append it to a variable. Print the value of the aggregated variable.

awk -v arr="BRB1 REZ3 SYO2" -F, 'BEGIN{split(arr,a," ")} {for (v in a) { if ($2 == substr(a[v],0,3)) {n=substr(a[v],length(a[v]),1); w=w""substr($1,n,1) }}} END{print w}' file.csv
umo

CodePudding user response:

Try this code:

#!/bin/bash
declare -A idx_dic
filename="$1"
pattern_string=""
for i in "${@:2}";
do
    pattern_words=$(echo "$i" | grep -oE '[A-Z] ')
    index=$(echo "$i" | grep -oE '[0-9] ')
    pattern_string =$(echo "$pattern_words|")
    idx_dic["$pattern_words"]="$index"
done
pattern_string=${pattern_string%|*}
while IFS= read -r line
do
    line_pattern=$(echo $line | grep -oE $pattern_string)
    [[ -n $line_pattern ]] && line_index="${idx_dic[$line_pattern]}" && echo $line | awk -v i="$line_index" '{split($0, chars, ""); printf("%s", chars[i]);}'
done < $filename
  • first find the capital words pattern and catch the index corresponding
  • then construct the hole pattern words string which connect with |
  • at last, iterate the every line according to the pattern string, and find the letter by the index

Execute this script.sh like:

bash script.sh file.csv BRB1 REZ3 SYO2
  •  Tags:  
  • bash
  • Related