Home Database Mysql Tutorial Bash实用技巧:同时循环两个列表

Bash实用技巧:同时循环两个列表

Jun 07, 2016 pm 03:10 PM
bash list Practical Tips cycle Summary

摘要: 你会学到一种原创的同时循环两个列表的方法。类似于Python或者Haskell的zip函数,非常简洁直观,效果如下: $ paste ( seq 1 5 ) ( seq 129 133 ) | while read host ip; do echo " vm$host: 172.16.116.$ip " ; done vm1: 172.16 . 116.129 vm2: 172

摘要:

你会学到一种原创的同时循环两个列表的方法。类似于Python或者Haskell的zip函数,非常简洁直观,效果如下:

$ paste seq <span>1</span> <span>5</span>) seq <span>129</span> <span>133</span>) | <span>while</span> read host ip; <span>do</span> <span>echo</span> <span>"</span><span>vm$host: 172.16.116.$ip</span><span>"</span>; <span>done</span><span>

vm1: </span><span>172.16</span>.<span>116.129</span><span>
vm2: </span><span>172.16</span>.<span>116.130</span><span>
vm3: </span><span>172.16</span>.<span>116.131</span><span>
vm4: </span><span>172.16</span>.<span>116.132</span><span>
vm5: </span><span>172.16</span>.<span>116.133</span>
Copy after login

详情:

在实际应用中,经常需要我们输入对应的两个列表,比如主机名和IP:

vm110 <span>172.18</span>.<span>11.129</span><span>

vm111 </span><span>172.18</span>.<span>11.130</span><span>

...</span>
Copy after login

如果有很多的话,使用awk处理一个临时文件,然后使用while read来循环是不错的(例如从Excel里面拷贝成文本文件,然后用awk提取相应的列到一个文件):

<span>awk</span> <span>'</span><span>{print $1 $3}</span><span>'</span> orig.txt | <span>while</span> read host ip; <span>do</span> <span>echo</span> $host : $ip; <span>done</span> 

<p>但是,有没有能直接在命令行上生成这些列表并循环的方法呢?因为我更喜欢用for i in vm{110..120}; do echo $i; done这种方式来循环列表,但是这种方式只支持一个列表,怎么找到对应的另一个列表呢?</p>
<p>直接google,就会发现没有什么好的方法(以下均来自StackOverflow):</p>
<p>1、有的直接使用bash的数组甚至hash表,都是较新的版本才有,然后使用数字index来循环。这种方法一点也不直观:</p>
<p>
</p><pre class="brush:php;toolbar:false">list1=<span>"</span><span>a b c</span><span>"</span><span>
list2</span>=<span>"</span><span>1 2 3</span><span>"</span><span>
array1</span>=<span>($list1)
array2</span>=<span>($list2)

count</span>=<span>${#array1[@]}
</span><span>for</span> i <span>in</span> `<span>seq</span> <span>1</span><span> $count`
</span><span>do</span>
    <span>echo</span> ${array1[$i-<span>1</span>]} ${array2[$i-<span>1</span><span>]}
</span><span>done</span>
Copy after login

谁也不想写类似${#array1[@]}这样的复杂表达,因为我们不是在编程,而是在输入一条命令。

2、有的使用了各种正则表达式命令,我一眼看不出来什么意思,没人会为了循环两个列表,去专门写一个脚本文件:

#!/bin/<span>sh</span><span>
list1</span>=<span>"</span><span>1 2 3</span><span>"</span><span>
list2</span>=<span>"</span><span>a b c</span><span>"</span>
<span>while</span> [ -n <span>"</span><span>$list1</span><span>"</span><span> ]
</span><span>do</span><span>
    head1</span>=`<span>echo</span> <span>"</span><span>$list1</span><span>"</span> | <span>cut</span> -d <span>'</span> <span>'</span> -f <span>1</span><span>`
    list1</span>=`<span>echo</span> <span>"</span><span>$list1</span><span>"</span> | <span>sed</span> <span>'</span><span>s/[^ ]* *\(.*\)$/\1/</span><span>'</span><span>`
    head2</span>=`<span>echo</span> <span>"</span><span>$list2</span><span>"</span> | <span>cut</span> -d <span>'</span> <span>'</span> -f <span>1</span><span>`
    list2</span>=`<span>echo</span> <span>"</span><span>$list2</span><span>"</span> | <span>sed</span> <span>'</span><span>s/[^ ]* *\(.*\)$/\1/</span><span>'</span><span>`
    </span><span>echo</span><span> $head1 $head2
</span><span>done</span>
Copy after login

还有其他几种,有兴趣的可以去看看,http://stackoverflow.com/questions/546817/iterating-over-two-lists-in-parallel-in-bin-sh。

但是有一种方法提醒了我:

list1=<span>"</span><span>aaa1 aaa2 aaa3</span><span>"</span><span>
list2</span>=<span>"</span><span>bbb1 bbb2 bbb3</span><span>"</span><span>

tmpfile1</span>=$( <span>mktemp</span> /tmp/list.XXXXXXXXXX ) || exit <span>1</span><span>
tmpfile2</span>=$( <span>mktemp</span> /tmp/list.XXXXXXXXXX ) || exit <span>1</span>

<span>echo</span> $list1 | <span>tr</span> <span>'</span> <span>'</span> <span>'</span><span>\n</span><span>'</span>  ><span> $tmpfile1
</span><span>echo</span> $list2 | <span>tr</span> <span>'</span> <span>'</span> <span>'</span><span>\n</span><span>'</span>  ><span> $tmpfile2

paste  $tmpfile1  $tmpfile2

</span><span>rm</span> --force $tmpfile1  $tmpfile2
Copy after login

这种方法创建了两个临时文件,好像还不如前面的方法,但是在我看来,这很有启发性:他使用了paste来结合两个列表,这是linux下原生的合并列表命令,相当于其他语言的zip。

另外,临时文件也可以避免,因此我想出了以下的方法(并不推荐):

paste echo vm{<span>1</span>..<span>5</span>} | <span>tr</span> <span>'</span> <span>'</span> <span>'</span><span>\n</span><span>'</span>) echo <span>172.16</span>.<span>116</span>.{<span>129</span>..<span>133</span>} | <span>tr</span> <span>'</span> <span>'</span> <span>'</span><span>\n</span><span>'</span>) | <span>while</span> read host ip; <span>do</span> <span>echo</span> $host: $ip; <span>done</span>
Copy after login

其中vm{1..5}会产生“vm1 vm2 vm3 vm4 vm5”,以空格分隔,而paste是把两个列文件合并成一个,所以必须把空格替换成换行,这就是tr做的事。明显使用tr很不好,增加了命令的复杂度。

另外

于是我想到了seq,好像可以指定分隔符,一查文档,居然默认就是换行,于是命令得以大幅简化:

paste seq <span>1</span> <span>5</span>) seq <span>129</span> <span>133</span>) | <span>while</span> read host ip; <span>do</span> <span>echo</span> <span>"</span><span>vm$host: 172.16.116.$ip</span><span>"</span>; <span>done</span><span><br></span>
Copy after login

这个命令可以循环2个及以上同等长度的列表,而且非常直观。就是开头提到的方法。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to remove square brackets from a list using Python How to remove square brackets from a list using Python Sep 05, 2023 pm 07:05 PM

Python is a very useful software that can be used for many different purposes depending on the need. Python can be used in web development, data science, machine learning, and many other fields that require automation. It has many different features that help us perform these tasks. Python lists are one of the very useful features of Python. As the name suggests, a list contains all the data you wish to store. It is basically a set of different types of information. Different Ways to Remove Square Brackets Many times, users come across a situation where list items are displayed within square brackets. In this article, we'll detail how to remove these brackets to get a better view of your listing. One of the easiest ways to remove parentheses in strings and replacement functions is in

How to count the number of elements in a list using Python's count() function How to count the number of elements in a list using Python's count() function Nov 18, 2023 pm 02:53 PM

How to use Python's count() function to calculate the number of an element in a list requires specific code examples. As a powerful and easy-to-learn programming language, Python provides many built-in functions to handle different data structures. One of them is the count() function, which can be used to count the number of elements in a list. In this article, we will explain how to use the count() function in detail and provide specific code examples. The count() function is a built-in function of Python, used to calculate a certain

Troubleshooting Tomcat 404 Errors: Quick and Practical Tips Troubleshooting Tomcat 404 Errors: Quick and Practical Tips Dec 28, 2023 am 08:05 AM

Practical Tips to Quickly Solve Tomcat404 Errors Tomcat is a commonly used JavaWeb application server and is often used when developing and deploying JavaWeb applications. However, sometimes we may encounter a 404 error from Tomcat, which means that Tomcat cannot find the requested resource. This error can be caused by multiple factors, but in this article, we will cover some common solutions and tips to help you resolve Tomcat 404 errors quickly. Check URL path

How to Make a Shopping List in the iOS 17 Reminders App on iPhone How to Make a Shopping List in the iOS 17 Reminders App on iPhone Sep 21, 2023 pm 06:41 PM

How to Make a GroceryList on iPhone in iOS17 Creating a GroceryList in the Reminders app is very simple. You just add a list and populate it with your items. The app automatically sorts your items into categories, and you can even work with your partner or flat partner to make a list of what you need to buy from the store. Here are the full steps to do this: Step 1: Turn on iCloud Reminders As strange as it sounds, Apple says you need to enable reminders from iCloud to create a GroceryList on iOS17. Here are the steps for it: Go to the Settings app on your iPhone and tap [your name]. Next, select i

Practical tips for efficiently solving Java large file reading exceptions Practical tips for efficiently solving Java large file reading exceptions Feb 21, 2024 am 10:54 AM

Practical tips for efficiently resolving large file read exceptions in Java require specific code examples. Overview: When processing large files, Java may face problems such as memory overflow and performance degradation. This article will introduce several practical techniques to effectively solve Java large file reading exceptions, and provide specific code examples. Background: When processing large files, we may need to read the file contents into memory for processing, such as searching, analyzing, extracting and other operations. However, when the file is large, the following problems are often encountered: Memory overflow: trying to copy the entire file at once

How to create a grocery list: Use the Reminders app for iPhone How to create a grocery list: Use the Reminders app for iPhone Dec 01, 2023 pm 03:37 PM

In iOS 17, Apple added a handy little list feature to the Reminders app to help you when you're out shopping for groceries. Read on to learn how to use it and shorten your trip to the store. When you create a list using the new "Grocery" list type (named "Shopping" outside the US), you can enter a variety of food and groceries and have them automatically organized by category. This organization makes it easier to find what you need at the grocery store or while out shopping. Category types available in alerts include Produce, Bread & Cereals, Frozen Foods, Snacks & Candy, Meat, Dairy, Eggs & Cheese, Baked Goods, Baked Goods, Household Products, Personal Care & Wellness, and Wine, Beer & Spirits . The following is created in iOS17

What is the difference between Del and remove() on lists in Python? What is the difference between Del and remove() on lists in Python? Sep 12, 2023 pm 04:25 PM

Before discussing the differences, let us first understand what Del and Remove() are in Python lists. Del Keyword in Python List The del keyword in Python is used to delete one or more elements from a List. We can also delete all elements, i.e. delete the entire list. Example of using del keyword to delete elements from a Python list #CreateaListmyList=["Toyota","Benz","Audi","Bentley"]print("List="

Create multiple directories from a list using Python Create multiple directories from a list using Python Sep 08, 2023 am 08:21 AM

Python has become one of the most popular programming languages ​​for various applications due to its simplicity and versatility. Whether you are an experienced developer or just starting out on your coding journey, Python offers a wide range of features and libraries that make complex tasks manageable. In this article, we will explore a practical scenario where Python can help us by automating the process of creating multiple directories based on a list. By leveraging the power of Python's built-in modules and techniques, we can handle this task efficiently without the need for manual intervention. In this tutorial, we will delve into the problem of creating multiple directories and provide you with different ways to solve this problem using Python. By the end of this article, our goal is for you

See all articles