我遇到问题,如果文本文件中的单词由制表符分隔,而不是空格,则程序无法读取每个单词。
例如,这里是文件。
part_Q.txt:
NWLR35MQ 649 HCDA93OW 526 abc 1 def 2 ghi 3 注意在“abc”和“1”之间,有一个标签,而不是空格。 还要注意,在“NWLR35MQ”和“649”之间,没有标签,但都是空格。 第二条线也是如此。输出:
NWLR35MQ 649 HCDA93OW 526 def 2 ghi 3但是,如果我用文件中的空格替换“abc”和“1”之间的tab,那么它会像下面那样正确输出,
预期产出:
NWLR35MQ 649 HCDA93OW 526 abc 1 def 2 ghi 3它正确显示文件中的所有单词。 如何显示所有单词而不管标签页或空格? 它应该在两种情况下显示所有单词。 看起来这个节目把tab当作一个角色。
以下是源代码:
#!/bin/sh tempCtr=0 realCtr=0 copyCtr=0 while IFS= read -r line || [[ -n $line ]]; do IFS=' ' tempCtr=0 for word in $line; do temp[$tempCtr]="$word" let "tempCtr++" done # if there are exactly 2 fields in each line, store ID and quantity if [ $tempCtr -eq 2 ] then part_Q[$realCtr]=${temp[$copyCtr]} let "realCtr++" let "copyCtr++" part_Q[$realCtr]=${temp[$copyCtr]} let "realCtr++" copyCtr=0 fi done < part_Q.txt for value in "${part_Q[@]}"; do echo $value doneI have problem on that the program cannot read each word if words in text file is spaced by tab, not space.
For example, here is file.
part_Q.txt:
NWLR35MQ 649 HCDA93OW 526 abc 1 def 2 ghi 3 note that between "abc" and "1", there is a tab, not space. Also note that between "NWLR35MQ" and "649", there is no tab but all are spaces. same for 2nd line as well.Output:
NWLR35MQ 649 HCDA93OW 526 def 2 ghi 3However, if I replace tab between "abc" and "1" by space in the file, then it outputs correctly like below,
Expected output:
NWLR35MQ 649 HCDA93OW 526 abc 1 def 2 ghi 3It correctly display all words in file. How can I display all words regardless of tab or space? it should display all words in both cases. It seems that the program regards tab as a character.
Below is source code:
#!/bin/sh tempCtr=0 realCtr=0 copyCtr=0 while IFS= read -r line || [[ -n $line ]]; do IFS=' ' tempCtr=0 for word in $line; do temp[$tempCtr]="$word" let "tempCtr++" done # if there are exactly 2 fields in each line, store ID and quantity if [ $tempCtr -eq 2 ] then part_Q[$realCtr]=${temp[$copyCtr]} let "realCtr++" let "copyCtr++" part_Q[$realCtr]=${temp[$copyCtr]} let "realCtr++" copyCtr=0 fi done < part_Q.txt for value in "${part_Q[@]}"; do echo $value done最满意答案
你想做什么? 如果输出是你唯一的目标,这可以很容易实现:
$ cat <<EOF | sed -E 's/[[:blank:]]+/\n/' NWLR35MQ 649 HCDA93OW 526 abc 1 def 2 ghi 3 EOF NWLR35MQ 649 HCDA93OW 526 abc 1 def 2 ghi 3Changing IFS=' ' to IFS=$'\t ' solved! thank you @anubhava
更多推荐
发布评论