简体   繁体   English

如果文本文件 bash 脚本中有多个列

[英]If multiple columns in text file bash scripting

How to detect multiple columns inside if statement for bash scripting?如何在用于 bash 脚本的 if 语句中检测多列? I want to do something if there are multiple columns inside the text file.如果文本文件中有多个列,我想做一些事情。

Example:例子:

I will output one command to file device.txt我将输出一个命令到文件 device.txt

If there is only one device, I will have just that name inside the document:如果只有一个设备,我将在文档中使用该名称:

Device1:

If I have multiple devices I will have this inside the device.txt file:如果我有多个设备,我会将它放在 device.txt 文件中:

Device1: Device2: Device3: 

I want to create if statement inside my bash script that will be triggered if there are multiple devices.我想在我的 bash 脚本中创建 if 语句,如果有多个设备,它将被触发。

if [[ `awk 'NF > 1' device.txt` ]]; then
    command
fi

awk while start printing anything whenever the number of fields of a line exceeds one. awk当一行的字段数超过 1 时开始打印任何内容。

You could make it more elegant by using {exit 1} as the awk command to execute whenever the condition applies, but it does make it harder to understand what's going on, as than there is 'false' exit code when the condition applied, since finding no columns results in a 'successful` execution of the awk program.您可以通过使用{exit 1}作为在条件适用时执行的awk命令使其更加优雅,但它确实使人们更难理解发生了什么,因为当条件适用时存在“假”退出代码,因为找不到列会导致 awk 程序“成功”执行。

最后我使用这个命令wc -w它做我需要的

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

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