列表

详情


SHELL17. 将字段逆序输出文件的每行

描述

将字段逆序输出文件nowcoder.txt的每一行,其中每一字段都是用英文冒号: 相分隔。
假设nowcoder.txt内容如下:
nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false
root:*:0:0:System Administrator:/var/root:/bin/sh
你的脚本应当输出
/usr/bin/false:/var/empty:Unprivileged User:-2:-2:*:nobody
/bin/sh:/var/root:System Administrator:0:0:*:root


原站题解

Bash 解法, 执行用时: 3ms, 内存消耗: 412KB, 提交时间: 2022-04-13

#!/bin/bash
# copied from discussion
IFS=":"
while read line
    do
        arr=($line)
        for ((i=${#arr[*]}-1; i>0; i--))
            do
                if [ ${arr[${i}]} == "nowcoder.txt" ];
                then
                    s="$s*:"
                    continue
                fi
                [ ${arr[${i}]} == "a.sh" ] && continue
                s="$s${arr[${i}]}:"
            done
        printf "$s${arr[0]}\n"
        s=""
    done

Bash 解法, 执行用时: 3ms, 内存消耗: 416KB, 提交时间: 2022-01-14

IFS=":"
while read line
do
arr=($line)
for((i = ${#arr[*]} - 1; i > 0; i--))
do
if [ ${arr[${i}]} == "nowcoder.txt" ]; then
s="$s*:"
continue
fi
[ ${arr[${i}]} == "a.sh" ] && continue
s="$s${arr[${i}]}:"
done
printf "$s${arr[0]}\n"
s=""
done

Bash 解法, 执行用时: 3ms, 内存消耗: 416KB, 提交时间: 2021-11-29

IFS=":"
while read line
    do
        arr=($line)
        for ((i=${#arr[*]}-1; i>0; i--))
            do
                if [ ${arr[${i}]} == "nowcoder.txt" ];then
                    s="$s*:"
                    continue
                fi
                [ ${arr[${i}]} == "a.sh" ] && continue
                s="$s${arr[${i}]}:"
            done
        printf "$s${arr[0]}\n"
        s=""
    done

Bash 解法, 执行用时: 3ms, 内存消耗: 420KB, 提交时间: 2022-03-18

while IFS=:&&read -a row
do
    IFS=" "
    reverseLine=""
    for ((i=${#row[@]}-1; i>=0; i--))
    do
        if [[ -n $reverseLine ]]
        then
            reverseLine+=:
        fi
        reverseLine+=${row[i]}
    done
    echo $reverseLine
done < nowcoder.txt

Bash 解法, 执行用时: 3ms, 内存消耗: 420KB, 提交时间: 2022-03-06

#!/bin/bash

OLD_IFS="$IFS"
IFS=":"

while read -a arr
do
    for (( i=${#arr[@]}-1;i>-1;i-- ))
    do
        echo -n "${arr[${i}]}"
        if (( ${i} != 0 ))
        then
            echo -n ":"
        fi
    done
    echo ""
done < nowcoder.txt

IFS="$OLD_IFS"

#while read line;
#do
#    readarray -d :  -t arr <<< "$line"
#    echo "line:${line}"
#    echo "len:${#arr[*]}"
#    for ((i = ${#arr[*]} - 1; i >= 0; i--));
#    do
#        if [ ${i} -eq 0 ]
#        then
#            echo "${arr["${i}"]}" | tr -d '\n';
#            break;
#        fi
#        echo "${arr["${i}"]}:" | tr -d '\n';
#        printf("%s:", ${arr[${i}]} );
#    done
#    echo ''
#done < nowcoder017.txt

上一题