AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / ubuntu / 问题 / 1194620
Accepted
zou hai
zou hai
Asked: 2019-12-08 19:10:55 +0800 CST2019-12-08 19:10:55 +0800 CST 2019-12-08 19:10:55 +0800 CST

您将如何分隔具有多个空格的字段并将它们存储在数组中?

  • 772

在我的文件中mytxt:

field1                    field2
------                    -------
this are numbers          12345
this letters              abc def ghi 

假设我想将第一个字段存储在数组中:

i=0
while read line; do 
    field_one[$i]=$(echo $line | awk '{print $1}')
    echo ${field_one[i]}  
    ((i++))
done < mytxt

那会给我this两次输出。

关于如何将它们存储在数组中并获得输出的任何想法:

this are numbers
this letters

我尝试过更改分隔符、压缩空格和使用sed,但我被卡住了。任何提示将不胜感激。

我的最终目标是将这两个字段存储在一个数组中。

bash sed awk tr cut-command
  • 4 4 个回答
  • 4040 Views

4 个回答

  • Voted
  1. user986805
    2019-12-08T21:13:28+08:002019-12-08T21:13:28+08:00

    使用 colrm 从文件中删除列。

    #!/bin/bash
    
    shopt -s extglob
    
    a=()
    while read; do
       a+=("${REPLY%%*( )}")
    done < <(colrm 26 < text.txt)
    
    printf %s\\n "${a[@]:2:3}"
    

    (Bash 内置版本):

    #!/bin/bash
    
    shopt -s extglob
    
    a=()
    while read; do
        b="${REPLY::26}"; a+=("${b%%*( )}")
    done < text.txt
    
    printf %s\\n "${a[@]:2:3}"
    
    • 4
  2. steeldriver
    2019-12-09T04:57:25+08:002019-12-09T04:57:25+08:00

    您可以将 bash 内置函数mapfile(aka readarray)与一个回调一起使用,该回调使用参数扩展来修剪以两个空格开头的最长尾随子字符串:

    mapfile -c 1 -C 'f() { field_one[$1]="${2%%  *}"; }; f' < mytxt
    

    前任。给定

    $ cat mytxt
    field1                    field2
    ------                    -------
    this are numbers          12345
    this letters              abc def ghi 
    

    然后

    $ mapfile -c 1 -C 'f() { field_one[$1]="${2%%  *}"; }; f' < mytxt
    $
    $ printf '%s\n' "${field_one[@]}" | cat -A
    field1$
    ------$
    this are numbers$
    this letters$
    
    • 2
  3. WinEunuuchs2Unix
    2019-12-09T07:57:22+08:002019-12-09T07:57:22+08:00

    这个答案的重点是从数组中删除两条标题线以匹配输出要求。

    $ cat fieldone.txt
    field1                    field2
    ------                    -------
    this are numbers          12345
    this letters              abc def ghi 
    
    $ fieldone
    this are numbers         
    this letters             
    

    这是脚本:

    #!/bin/bash
    
    # NAME: fieldone
    # PATH: $HOME/askubuntu/
    # DESC: Answer for: https://askubuntu.com/questions/1194620/
    # how-would-you-separate-fields-with-multiple-spaces-and-store-them-in-an-array
    
    # DATE: December 8, 2019.
    
    i=0                                     # Current 0-based array index number
    while read line; do                     # Read all lines from input file
        ((LineNo++))                        # Current line number of input file
        [[ $LineNo -eq 1 ]] && continue     # "Field 1     Field 2" skip first line
        if [[ $LineNo -eq 2 ]] ; then       # Is this is line 2?
            # Grab the second column position explained in:
            # https://unix.stackexchange.com/questions/153339/
            # how-to-find-a-position-of-a-character-using-grep
            Len="$(grep -aob ' -' <<< "$line" | \grep -oE '[0-9]+')"
            continue                        # Loop back for first field
        fi
    
        field_one[$i]="${line:0:$Len}"      # Extract line position 0 for Len
        echo "${field_one[i]}"              # Display array index just added
        ((i++))                             # Increment for next array element
    
    done < fieldone.txt                     # Input filename fed into read loop
    

    希望代码和注释是不言自明的。如果没有,请不要犹豫发表评论。

    如果只有一个空格将两列隔开,该脚本仍然有效,而其他一些答案将中断:

    field1         field2
    ------         ------
    this is letter abcdef
    this is number 123456
    
    • 2
  4. Best Answer
    Pablo Bianchi
    2019-12-10T09:36:12+08:002019-12-10T09:36:12+08:00

    移动我的评论,基于这个来源,只在基于多空格的表上显示一个特定的列:

    awk -F '  +' '{print $2}' mytxt.txt  # Or with -F ' {2,}'
    

    请注意,如果您使用双引号,这将不起作用。

    我发现使用以下方法查找重复项特别有用:

    somelist... | sort | uniq -c | sort -rn | grep -vP "^ +1 " | awk -F '  +' '{print $3}'
    
    • 2

相关问题

  • 同时复制到两个位置

  • 如何在 shell 脚本中创建选择菜单?

  • 从 bash 迁移到 zsh [关闭]

  • bashrc 还是 bash_profile?

  • 备份 bash 脚本未压缩其 tarball

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    如何运行 .sh 脚本?

    • 16 个回答
  • Marko Smith

    如何安装 .tar.gz(或 .tar.bz2)文件?

    • 14 个回答
  • Marko Smith

    如何列出所有已安装的软件包

    • 24 个回答
  • Marko Smith

    无法锁定管理目录 (/var/lib/dpkg/) 是另一个进程在使用它吗?

    • 25 个回答
  • Martin Hope
    Flimm 如何在没有 sudo 的情况下使用 docker? 2014-06-07 00:17:43 +0800 CST
  • Martin Hope
    Ivan 如何列出所有已安装的软件包 2010-12-17 18:08:49 +0800 CST
  • Martin Hope
    La Ode Adam Saputra 无法锁定管理目录 (/var/lib/dpkg/) 是另一个进程在使用它吗? 2010-11-30 18:12:48 +0800 CST
  • Martin Hope
    David Barry 如何从命令行确定目录(文件夹)的总大小? 2010-08-06 10:20:23 +0800 CST
  • Martin Hope
    jfoucher “以下软件包已被保留:”为什么以及如何解决? 2010-08-01 13:59:22 +0800 CST
  • Martin Hope
    David Ashford 如何删除 PPA? 2010-07-30 01:09:42 +0800 CST

热门标签

10.10 10.04 gnome networking server command-line package-management software-recommendation sound xorg

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve