在bash和阵列工作做的东西 [英] working with arrays in bash and do stuff

查看:105
本文介绍了在bash和阵列工作做的东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个bash脚本和需要帮助。这是我尝试:

I am writing a bash script and need help. This is what I tried:

使用@ merlin2011

With the help of @merlin2011

#!/bin/bash

if [ $# -ne 2 ]; then
    echo "Usage: `basename $0` <absolute-path> <number>"
    exit 1
fi

if [ "$(id -u)" != "0" ]; then
    echo "This script must be run as root" 1>&2
    exit 1
fi

#find . -name "$2" -exec mv {} /some/path/here \;
find $1 >> /tmp/test
for line in $(cat `/tmp/test`); do
    echo $line | mv $2 awk -F"/" '{for (i = 1; i < NF; i++) if ($i == "$2") print $(i-1)}'
done

现在我要检查的结果找到从阵列命令,然后如果有一个名为 2010 然后得到它的绝对路径。对于ecxample:

Now I want to check the result of find command from array and then if there were a directory named 2010 then get the absolute path of it. For ecxample:

arr[1]="/path/to/2010/file.db"

然后我要重命名 2010 来的父目录。我的模式是:

Then I want to rename 2010 to parent directory to. My pattern is:

arr[1]="/path/to/2010/file.db"
arr[2]="/path/test/2010/fileee.db"
arr[3]="/path/tt/2010/fileeeee.db"
.
.
.
arr[100]="/path/last/2010/fileeeeeee.db"

结果应该是:

mv /path/to/2010/ to
mv /path/test/2010 test
mv /path/tt/2010/ tt
.
.
.
mv /path/last/2010 last

更新:

完全我想知道如何在 AWK ...

Totally I want to know how to get a variable inversely in awk...

/path/to/dir1/2010/file.db

我想在的绝对路径搜索然后找到2010年和它在previous路径以 / 重命名模式,如:awk的-F/{打印[什么?]}

I want to search in absolute path then find 2010 and rename it in previous path with / pattern like : awk -F"/" {print [what?]}

告诉我的awk的状态,然后2010通过了解分离器之前,打印一个变量是 /

tell awk my state is 2010 then print one variable before it by knowing splitter is /

该文件显示目录和子目录的模式是:

The files dirs and subdirs pattern are:

/path/to/file/efsef/2010/1.db
/path/to/file/hfjh/sdfsf/2010/2.db
/path/to/file/dsf/sdhher/aqwe/sfrt/2010/3.db
.
.
.
/path/to/file/kldf/2010/100.db

我要重命名所有2010迪尔斯他们的父母则焦油所有 .db的

这是我想要什么:)

推荐答案

这答案地址只有OP的更新。我最好的跨pretation是,你试图让 AWK 来打印字符串中的数值 DIR1 /path/to/dir1/2010/file.db 。下面的线将实现它。

This answer addresses only the OP's update. My best interpretation is that you are trying to get awk to print the value dir1 inside the string /path/to/dir1/2010/file.db. The following line will achieve it.

awk -F"/" '{for (i = 1; i < NF; i++) if ($i == "2010") print $(i-1)}'

我测试使用下面的命令,将输出 DIR1

echo /path/to/dir1/2010/file.db | awk -F"/" '{for (i = 1; i < NF; i++) if ($i == "2010") print $(i-1)}'

根据您的更新,你应该与周围的 backtic 运营商 AWK 命令。

Based on your update, you should surround the awk command with the backtic operator.

mv $2 `awk -F"/" '{for (i = 1; i < NF; i++) if ($i == "$2") print $(i-1)}'`

这篇关于在bash和阵列工作做的东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆