如何替换Linux管道分隔文件中的非分隔符管道(|)为短横线(-)
处理带引号的管道分隔文件:替换非分隔符管道为短横线
问题场景
我们有以管道|为分隔符的文本文件,但部分被双引号包裹的字段内部包含管道字符,这些管道不是分隔符,需要替换为短横线-。作为分隔符的管道始终位于两个双引号之间(格式为"xxx"|"yyy")。
示例输入
col1|col2|col3|col4 "1"|"This is my column 2 |Although there is pipe here, it is not a delimiter pipe."|"And this is my 3rd column '|" with a pipe followed by a double quote"|"|and finally this 4th column starts with a | that is not'|a delimiter
期望输出
col1|col2|col3|col4 "1"|"This is my column 2 -Although there is pipe here, it is not a delimiter pipe."|"And this is my 3rd column '-" with a pipe followed by a double quote"|"-and finally this 4th column starts with a - that is not'-a delimiter
解决方案:用AWK脚本处理
使用AWK逐个字符遍历,跟踪是否处于双引号内部,仅替换引号内的管道:
awk -F '' '{ in_quote = 0 for (i=1; i<=NF; i++) { if ($i == "\"") { in_quote = !in_quote } if (in_quote && $i == "|") { $i = "-" } } print }' input_file > output_file
脚本逻辑说明
-F '':将每行拆分为单个字符的字段,方便逐个处理in_quote变量:标记当前是否处于双引号内部(0=不在,1=在)- 遍历每个字符:
- 遇到双引号时,切换
in_quote状态(进入/退出引号区域) - 若当前在引号内且字符是
|,则替换为-
- 遇到双引号时,切换
- 打印处理后的整行
该脚本能精准区分分隔符管道和字段内管道,不受字段内其他字符(空格、单引号等)影响。
内容的提问来源于stack exchange,提问作者Selim
相关产品推荐
相关产品推荐

