如果按标签隔开,则无法识别单词(Cannot recognize word if spaced by tab)

编程入门 行业动态 更新时间:2024-10-05 19:15:26
如果按标签隔开,则无法识别单词(Cannot recognize word if spaced by tab)

我遇到问题,如果文本文件中的单词由制表符分隔,而不是空格,则程序无法读取每个单词。

例如,这里是文件。

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 done

I 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 3

However, 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 3

It 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 3

Changing IFS=' ' to IFS=$'\t ' solved! thank you @anubhava

更多推荐

本文发布于:2023-08-07 18:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465246.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单词   无法识别   标签   recognize   spaced

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!