简体   繁体   English

Bash字符串中的条件报价

[英]Bash Conditional Quote in String

I have a CSV file that I'm parsing in bash that, for one column, has more than one value for some rows. 我有一个正在bash中解析的CSV文件,对于一列,某些行具有多个值。 For example, a line with multiple values may look like 例如,具有多个值的线可能看起来像

name,12,120,east,"sw1,sw2,sw3"

But not all rows have it. 但并非所有行都有它。 Some may look like 有些可能看起来像

name,10,141,west,sw5534a

What I'm trying to do is if that column has quotes in it to remove them and set the variable to just sw1,sw2,sw3 我想做的是,如果该列中有引号将其删除,并将变量设置为sw1,sw2,sw3

Relevant parts of the script: 脚本的相关部分:

#!/bin/bash
INPUT=file.csv
OLDIFS=$IFS
IFS=,
[ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99; }
while read name building id region parents
do
echo "
....snip....
parents $parents"

The output I want for $parents should be sw1,sw2,sw3 but right now it spits out as "sw1,sw2,sw3" I've tried messing around with regex matching in a conditional if the column has a comma to remove the first and last two characters, but I couldn't get it to work. 我想要给$ parents的输出应该是sw1,sw2,sw3但现在它吐出为"sw1,sw2,sw3"如果列中有逗号,则我尝试用有条件的正则表达式进行修改最后两个字符,但我无法正常工作。 Either it would remove the first s and the last 3 or it would just error out. 它会删除前s和后3 ,否则会出错。

Any suggestions appreciated! 任何建议表示赞赏!

You can remove both instances of the " character in the $parents variable with substring replacement: 您可以通过替换子字符串来删除$parents变量中"字符的两个实例:

echo ${parents//\"/}

This replaces all " characters with the empty string. 这将替换所有的"字符用空字符串。

parents="${parents#\"}"
parents="${parents%\"}"

This will remove the first character if a quote, and the last character if a quote. 如果有引号,则将删除第一个字符;如果有引号,则将删除最后一个字符。 If they are not a quote, they will be left untouched. 如果它们不是引号,则将保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM