如何在shell中以数组形式传递单词时删除单词的空间 [英] How to remove space from word while passing it in array in shell

查看:101
本文介绍了如何在shell中以数组形式传递单词时删除单词的空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关从文件中读取文本并将其传递到带有空格的数组中的帮助.

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

我的文件是:

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

我的代码是:

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[@]}

输出为

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

echo ${Name[@]}输入中

我希望输出为

Guru Singh Raju Deepak

有任何想法/帮助吗?

推荐答案

由于awk脚本执行了从文件中提取列的操作,因此您可以扩展它以提取带引号的字符串.通常,使用FPAT.这比Inder提案要复杂得多,但是将允许扩展数据,并支持任何列中的空格.

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.

还请注意,如果输入数据包含空格,则最好使用不会出现在数据中的其他定界符(例如,制表符\ t,冒号或类似符号).在大多数Unix工具中,解析引用的文本不是自然的".

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

这篇关于如何在shell中以数组形式传递单词时删除单词的空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆