简体   繁体   English

如何检查值是否包含 bash 中的字符

[英]How to check if a value contains characters in bash

I have values such as我有这样的价值观

B146XYZ, G638XYZ, G488xBC B146XYZ、G638XYZ、G488xBC

I have to write a bash script where when it sees comma it has to remove the comma and add 7 spaces to it and also if it sees comma and a space or just space(no punctuations) it has to add 7 spaces to make all of them fixed length.我必须编写一个 bash 脚本,当它看到逗号时,它必须删除逗号并添加 7 个空格,如果它看到逗号和一个空格或只是空格(没有标点符号),则它必须添加 7 个空格才能使所有的它们固定长度。

if [[  $row = *’,’* ]]
then
first= “${ row%%,*}”
echo “${first }       “

I tried but can't understand how to add conditions for the remaining criteria specially struggling with single value conditions such as G488xBC我尝试过但无法理解如何为其余标准添加条件,特别是在 G488xBC 等单值条件下挣扎

What about just:怎么样:

sed -E 's/[, ]+/       /g' file

Or something like this will print a padded table, so long as no field is longer than 13 characters:或者像这样的东西将打印一个填充表,只要没有字段超过 13 个字符:

awk -F '[,[:space:]]+' \
'{
    for (i=1; i<NF; i++) {
        printf("%-14s", $i)
    }

    print $NF
}'

Or the same thing in pure bash:或者在纯 bash 中做同样的事情:

while IFS=$', \t' read -ra vals; do
    last=$((${#vals[@]} - 1))

    for ((i=0; i<last; i++)); do
        printf "%-14s" "${vals[i]}"
    done

    printf '%s\n' "${vals[last]}"
done
newrow="${row//,/ }"
    VALUES=`echo $VALUES | sed 's/,/ /g' | xargs`
  • The sed command will replace the comma with a single space. sed 命令将用一个空格替换逗号。
  • The xargs will consolidate any number of whitespaces into a single space. xargs 会将任意数量的空格合并为一个空格。

With that you now have your values in space separated string instead of comma, separated by unknown number of whitespaces.有了这个,您现在可以将值以空格分隔的字符串而不是逗号分隔,并由未知数量的空格分隔。

From there you can use for i in $VALUES; do printf "$i\\t"; done从那里你可以for i in $VALUES; do printf "$i\\t"; done使用for i in $VALUES; do printf "$i\\t"; done for i in $VALUES; do printf "$i\\t"; done

Using the tab character like above will give you aligned output in case your values may be different in length.使用上面的制表符将为您提供对齐的输出,以防您的值的长度可能不同。

But if your values are always same length then you can make it a bit more simple by doing但是如果你的值总是相同的长度,那么你可以通过这样做让它更简单一点

    VALUES=`echo $VALUES | sed 's/,/ /g' | xargs | sed 's/1 space/7 spaces/g'`
    echo $VALUES

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

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