ORS拒绝将输出记录分成新行(ORS refuse to separate output record to new line)

系统教程 行业动态 更新时间:2024-06-14 17:02:18
ORS拒绝将输出记录分成新行(ORS refuse to separate output record to new line)

大家好我有这个文件:

paumic@os:~/l26$ cat p1 cat dog cow cat dog mouse dog cow cat

所以我想要做的是获得前2列并让它们像这样:

cat dog cat dog dog cow

当我使用我的脚本时:

paumic@os:~/l26$ cat skript #!/bin/sh output=$(cat $1 | awk 'BEGIN{ORS="\n"} {print $1, $2}' ) echo $output

我得到答案:

paumic@os:~/l26$ ./skript p1 cat dog cat dog dog cow

如果我使用别的东西而不是\n它的工作原理。 例:

paumic@os:~/l26$ cat skript #!/bin/sh output=$(cat $1 | awk 'BEGIN{ORS="()"} {print $1, $2}' ) echo $output paumic@os:~/l26$ ./skript p1 cat dog()cat dog()dog cow() paumic@os:~/l26$

谢谢你的时间和帮助。

Hello guys i have this file:

paumic@os:~/l26$ cat p1 cat dog cow cat dog mouse dog cow cat

so what I want to do is to get first 2 columns and have them like this:

cat dog cat dog dog cow

when i use my script which is:

paumic@os:~/l26$ cat skript #!/bin/sh output=$(cat $1 | awk 'BEGIN{ORS="\n"} {print $1, $2}' ) echo $output

i get answer:

paumic@os:~/l26$ ./skript p1 cat dog cat dog dog cow

If I use something else instead of \n it works. Example:

paumic@os:~/l26$ cat skript #!/bin/sh output=$(cat $1 | awk 'BEGIN{ORS="()"} {print $1, $2}' ) echo $output paumic@os:~/l26$ ./skript p1 cat dog()cat dog()dog cow() paumic@os:~/l26$

Thank you for you time and help.

最满意答案

总是引用你的变量。 它可能并不总是需要,但它是一个更安全的习惯。

此外,您可以简化您对awk的使用,并隐式包含对缺少选项的错误处理:

output=$(awk 'BEGIN{ORS="\n"} {print $1 ORS $2}' "${1:?No file provided}" ) echo "$output"

虽然明确处理错误可能会更好:

#!/bin/sh if [ -z "$1" ]; then echo "ERROR: no file specified" >&2 exit 1 elif [ ! -f "$1" ]; then echo "ERROR: no such file '$1'" >&2 exit 1 elif [ ! -r "$1" ]; then echo "ERROR: file unreadable: '$1'" >&2 exit 1 elif [ ! -s "$1" ]; then echo "WARNING: file empty: '$1'" >&2 fi output=$(awk -v ORS="\n" '{print $1,$2}' "$1" ) echo "$output"

Always quote your variables. It may not always be required, but it's a much safer habit to be in.

Also, you can streamline your use of awk and include error handling for missing options implicitly:

output=$(awk 'BEGIN{ORS="\n"} {print $1 ORS $2}' "${1:?No file provided}" ) echo "$output"

Though it would probably be better to be explicit with your error handling:

#!/bin/sh if [ -z "$1" ]; then echo "ERROR: no file specified" >&2 exit 1 elif [ ! -f "$1" ]; then echo "ERROR: no such file '$1'" >&2 exit 1 elif [ ! -r "$1" ]; then echo "ERROR: file unreadable: '$1'" >&2 exit 1 elif [ ! -s "$1" ]; then echo "WARNING: file empty: '$1'" >&2 fi output=$(awk -v ORS="\n" '{print $1,$2}' "$1" ) echo "$output"

更多推荐

本文发布于:2023-04-21 18:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/5ce2439643adbb8f66a0c8c5d37c62de.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:成新   refuse   ORS   separate   line

发布评论

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

>www.elefans.com

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