linux 逗号分隔,linux-如何用逗号分割列表而不是sp
linux-如何用逗號分割列表而不是sp
我想用,分隔文本,而不是for foo in list中的。假設我有一個CSV文件CSV_File,其中包含以下文本:
Hello,World,Questions,Answers,bash shell,script
...
我使用以下代碼將其拆分為幾個詞:
for word in $(cat CSV_File | sed -n 1'p' | tr ',' '\n')
do echo $word
done
它打印:
Hello
World
Questions
Answers
bash
shell
script
但我希望它用逗號而不是空格分隔文本:
Hello
World
Questions
Answers
bash shell
script
我如何在bash中實現這一目標?
7個解決方案
48 votes
將IFS設置為:
sorin@sorin:~$ IFS=',' ;for i in `echo "Hello,World,Questions,Answers,bash shell,script"`; do echo $i; done
Hello
World
Questions
Answers
bash shell
script
sorin@sorin:~$
Sorin answered 2020-07-29T02:47:50Z
46 votes
使用subshell替換來解析單詞會撤消將空格放在一起的所有工作。
請嘗試:
cat CSV_file | sed -n 1'p' | tr ',' '\n' | while read word; do
echo $word
done
這也增加了并行度。 在問題中使用subshell會強制完成整個subshell過程,然后才能開始遍歷答案。 通過管道連接到子外殼(如我的回答),它們可以并行工作。 當然,這僅在文件中有很多行時才重要。
mkj answered 2020-07-29T02:47:30Z
17 votes
我認為規范的方法是:
while IFS=, read field1 field2 field3 field4 field5 field6; do
do stuff
done < CSV.file
如果您不知道或不在乎有多少個字段:
IFS=,
while read line; do
# split into an array
field=( $line )
for word in "${field[@]}"; do echo "$word"; done
# or use the positional parameters
set -- $line
for word in "$@"; do echo "$word"; done
done < CSV.file
glenn jackman answered 2020-07-29T02:48:14Z
10 votes
kent$ echo "Hello,World,Questions,Answers,bash shell,script"|awk -F, '{for (i=1;i<=NF;i++)print $i}'
Hello
World
Questions
Answers
bash shell
script
Kent answered 2020-07-29T02:48:30Z
7 votes
創建一個bash函數
split_on_commas() {
local IFS=,
local WORD_LIST=($1)
for word in "${WORD_LIST[@]}"; do
echo "$word"
done
}
split_on_commas "this,is a,list" | while read item; do
# Custom logic goes here
echo Item: ${item}
done
...這將產生以下輸出:
Item: this
Item: is a
Item: list
(注意,此答案已根據一些反饋進行了更新)
Andrew Newdigate answered 2020-07-29T02:48:58Z
5 votes
閱讀:[http://linuxmanpages.com/man1/sh.1.php]&[http://www.gnu.org/s/hello/manual/autoconf/Special-Shell-Variables.html]
IFS內部字段分隔符,用于單詞拆分 擴展后,將行與單詞拆分成單詞 內置命令。 默認值為``''。
IFS是一個Shell環境變量,因此它將在Shell腳本的上下文中保持不變,但在其他情況下將保持不變,除非您將其導出。 還請注意,IFS根本不會從您的環境繼承:請參閱此gnu帖子,以獲取有關IFS的原因和更多信息。
您的代碼是這樣寫的:
IFS=","
for word in $(cat tmptest | sed -n 1'p' | tr ',' '\n'); do echo $word; done;
應該可以工作,我在命令行上對其進行了測試。
sh-3.2#IFS=","
sh-3.2#for word in $(cat tmptest | sed -n 1'p' | tr ',' '\n'); do echo $word; done;
World
Questions
Answers
bash shell
script
Ashley Raiteri answered 2020-07-29T02:49:37Z
0 votes
您可以使用:
cat f.csv | sed 's/,/ /g' | awk '{print $1 " / " $4}'
要么
echo "Hello,World,Questions,Answers,bash shell,script" | sed 's/,/ /g' | awk '{print $1 " / " $4}'
這是用空格替換逗號的部分
sed 's/,/ /g'
ozma answered 2020-07-29T02:50:05Z
總結
以上是生活随笔為你收集整理的linux 逗号分隔,linux-如何用逗号分割列表而不是sp的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一、数组经典题型
- 下一篇: Linux文件打补丁