按字母顺序进行AWK字符串比较

时间:2017-12-03 12:20:59

标签: linux string bash awk

问题很简单。 我有一个 AWK脚本,我有两个字符串(名称)。如果它们具有相同的长度,我需要根据ASCII选择“早一点 in aplhabet

第一个例子:

 1st string = "aac", 2nd string = "aab"

结果:aab

第二个例子:

1st string = "Donald J Cat", 2nd string = "Donald J Bat"

结果:Donald J Bat

在AWK中有一种简单的方法吗?

3 个答案:

答案 0 :(得分:1)

使用awk:

<?php

session_start();

include_once  'constants.php';
include_once 'connection.php';

$connection = new database();

$connection->connect();

$email = $_POST['email'];
$password = $_POST['password'];

// Call the login stored procedure
$conn = $connection->query("CALL LoginUser('$email','$password')");

//Check if any users match
$rows = mysqli_num_rows($conn);
if($rows > 0){

// If result was found put information into array
$user = mysqli_fetch_assoc($conn);

//Store all the users info in session variables
$_SESSION['user_id'] = $user['account_id'];
$_SESSION['user_firstName'] = $user['fname'];
$_SESSION['user_lastName'] = $user['lname'];
$_SESSION['user_password'] = $user['password'];
$_SESSION['user_dob'] = $user['dob'];
$_SESSION['user_joinDate'] = $user['joinDate'];
$_SESSION['user_picture'] = $user['picture'];

//Redirect user to logged in home page
header('Location: home.php');

// If no results are found redirect user to noAccount page
} else {
header('Location: noAccount.php');
}


?>

答案 1 :(得分:0)

假设比较字段是第一个和第二个,打印较短的字段,或者基于词法顺序(也就是字典顺序)等长的字段

/code/jk/jk/static

如果您希望对awk '... len1=length($1); len2=length($2); f = len1<len2 || (len1==len2 && $1<$2); print f?$1:$2; ...'

进行不区分大小写的更改

答案 2 :(得分:0)

如果您只处理两个字符串,则可以使用awk的字符串比较行为和三元组按照您描述的顺序将两个字符串分配给单个字符串:

$ echo "aac,aab
Donald J Cat,Donald J Bat
zoom batman,ahem Mr President
zzzzzz,a
aa,z" | awk -F, '{s=$1<$2 ? $1 "," $2 : $2 "," $1; print s}'
aab,aac
Donald J Bat,Donald J Cat
ahem Mr President,zoom batman
a,zzzzzz
aa,z

这将以asciibetical顺序打印两个单词; a胜出zzzz

如果您想排序多个字符串,并且最近有gawk vs POSIX awk,则可以使用PROCINFO遍历按值排序的数组:

echo "aac,aab,Donald J Cat,Donald J Bat
zoom batman,ahem Mr President,zzzzzz,a,aa,zz" | awk -F, '{s="";split("",a);
                                                    for (i=1;i<=NF;i++) a[i]=$i
                                                    PROCINFO["sorted_in"] = "@val_num_asc"
                                                    for (e in a) s=s a[e] ","
                                                    print gensub(",$","","1",s)}'
Donald J Bat,Donald J Cat,aab,aac
a,aa,ahem Mr President,zoom batman,zz,zzzzzz

请注意,在asciibetical sort 'D'<'a'中。在gawk中,如果需要,可以很容易地编写自定义比较函数。