How to remove space from word while passing it in array in shell

ぐ巨炮叔叔 提交于 2020-01-24 21:46:44

问题


I am looking for help in reading text from file and passing it into array with space in it.

My file is :

Pool    Library Name
Backup  Lib1    "Guru Singh"
clone   Lib2    Raju
Tape    Lib3    Deepak

My Code is :

column=1
for arrayname in Pool Library Name; do
     mapfile -t "$arrayname" < <(awk "NR > 1 {print \$$column}" file.txt)
     ((column++))
done
echo ${Pool[@]}
echo ${Library[@]}
echo ${Name[@]}

Output is

[root@Server MM]#     echo ${Pool[@]}
Backup clone Tape
[root@Server MM]#     echo ${Library[@]}
Lib1 Lib2 Lib3
[root@Server MM]#     echo ${Name[@]}
" Raju Deepak

In echo ${Name[@]} input

I want output as

Guru Singh Raju Deepak

Any Idea/Help?


回答1:


The following contents in a file named file.txt

The following line of code will give the output as:

awk '{ if ( NR!=1 ) { print $3 " " $4 } }' ORS=" " file.txt

Output:

"Guru Singh" Raju  Deepak

Explanation:

  1. if ( NR!=1 ) : meaning don't print the first row
  2. { print $3 " " $4 } : to print the column with names and an extension if required as is the first line. (This is a very specific solution use escaping quotes if more diverse cases exist in file.)
  3. ORS=" " : creates the output in a single line ORS stands for Output records separators, by default it is \n or next-line, we have set it to a space or " "

If you don't want the quotes in the output a quick fix can be to use tr for example:

awk '{ if ( NR!=1 ) { print $3 " " $4 } }' ORS=" " file | tr -d '"'

The Output:

Guru Singh Raju  Deepak



回答2:


Since the awk scriptlet perform the extraction of the column from the file, you can extend it to extract quoted strings. Normally, using FPAT. This is more complex than Inder proposal, but will allow the data to be extended, will support spaces in any column.

Also note, as alternative, that if your input data contain space, it might be a good idea to use a different delimiter (e.g., tab \t, colon, or similar) that will not appear in the data. Parsing quoted text is not "natual" with most Unix tools.

awk -v COL=$column -v 'FPAT=("[^"]*"|[^ ]*) *' 'NR>1 { v=$(COL) ; gsub(" *$", "", v) ; print v }' file.txt

Slightly rearranging the read might be easier to follow

column=1
for arrayname in Pool Library Name; do
     mapfile -t "$arrayname" <<< "$(awk -v COL=$column -v 'FPAT=("[^"]*"|[^ ]*) *' 'NR>1 { v=$(COL) ; gsub(" *$", "", v) ; gsub("\"", "", v) ; print v }' file.txt)"
     ((column++))
done


来源:https://stackoverflow.com/questions/59021512/how-to-remove-space-from-word-while-passing-it-in-array-in-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!